using System;
using System.Collections.Generic;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using TenantManagementService.Tenants;

namespace TenantManagementService.Tenants
{
    /// <summary>
    /// 租户实体
    /// </summary>
    public class Tenant : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID（ABP框架使用）
        /// </summary>
        public Guid? TenantId { get; protected set; }

        /// <summary>
        /// 租户编码（唯一标识）
        /// </summary>
        public string Code { get; protected set; } = string.Empty;

        /// <summary>
        /// 租户名称
        /// </summary>
        public string Name { get; protected set; } = string.Empty;

        /// <summary>
        /// 租户描述
        /// </summary>
        public string? Description { get; protected set; }

        /// <summary>
        /// 租户类型
        /// </summary>
        public TenantType Type { get; protected set; } = TenantType.Basic;

        /// <summary>
        /// 租户状态
        /// </summary>
        public TenantStatus Status { get; protected set; } = TenantStatus.Initializing;

        /// <summary>
        /// 租户Logo URL
        /// </summary>
        public string? LogoUrl { get; protected set; }

        /// <summary>
        /// 租户主题配置
        /// </summary>
        public string? ThemeSettings { get; protected set; }

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string? ConnectionString { get; protected set; }

        /// <summary>
        /// 主机地址
        /// </summary>
        public string? Host { get; protected set; }

        /// <summary>
        /// 租户管理员邮箱
        /// </summary>
        public string? AdminEmail { get; protected set; }

        /// <summary>
        /// 租户管理员手机号
        /// </summary>
        public string? AdminPhoneNumber { get; protected set; }

        /// <summary>
        /// 最大用户数
        /// </summary>
        public int MaxUserCount { get; protected set; } = 100;

        /// <summary>
        /// 当前用户数
        /// </summary>
        public int CurrentUserCount { get; protected set; } = 0;

        /// <summary>
        /// 最大存储空间（MB）
        /// </summary>
        public long MaxStorageSize { get; protected set; } = 1024; // 1GB

        /// <summary>
        /// 当前存储使用量（MB）
        /// </summary>
        public long CurrentStorageUsage { get; protected set; } = 0;

        /// <summary>
        /// 试用开始时间
        /// </summary>
        public DateTime? TrialStartTime { get; protected set; }

        /// <summary>
        /// 试用结束时间
        /// </summary>
        public DateTime? TrialEndTime { get; protected set; }

        /// <summary>
        /// 订阅开始时间
        /// </summary>
        public DateTime? SubscriptionStartTime { get; protected set; }

        /// <summary>
        /// 订阅结束时间
        /// </summary>
        public DateTime? SubscriptionEndTime { get; protected set; }

        /// <summary>
        /// 租户设置（JSON格式）
        /// </summary>
        public string? Settings { get; protected set; }

        /// <summary>
        /// 功能开关（JSON格式）
        /// </summary>
        public string? FeatureSwitches { get; protected set; }

        /// <summary>
        /// 自定义属性（JSON格式）
        /// </summary>
        public string? CustomProperties { get; protected set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; protected set; } = true;

        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime? LastAccessTime { get; protected set; }

        /// <summary>
        /// 最后激活时间
        /// </summary>
        public DateTime? LastActivationTime { get; protected set; }

        /// <summary>
        /// 延期次数
        /// </summary>
        public int ExtensionCount { get; protected set; } = 0;

        protected Tenant()
        {
        }

        public Tenant(
            Guid id,
            string code,
            string name,
            TenantType type = TenantType.Basic
        ) : base(id)
        {
            Code = Check.NotNullOrWhiteSpace(code, nameof(code));
            Name = Check.NotNullOrWhiteSpace(name, nameof(name));
            Type = type;
            Status = TenantStatus.Initializing;
            CreationTime = DateTime.Now;
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        public virtual Tenant UpdateBasicInfo(string name, string? description = null, string? logoUrl = null)
        {
            Name = Check.NotNullOrWhiteSpace(name, nameof(name));
            Description = description;
            LogoUrl = logoUrl;
            return this;
        }

        /// <summary>
        /// 更新租户状态
        /// </summary>
        public virtual Tenant UpdateStatus(TenantStatus status)
        {
            Status = status;

            if (status == TenantStatus.Active && !LastActivationTime.HasValue)
            {
                LastActivationTime = DateTime.Now;
            }

            return this;
        }

        /// <summary>
        /// 激活租户
        /// </summary>
        public virtual Tenant Activate()
        {
            Status = TenantStatus.Active;
            IsEnabled = true;
            LastActivationTime = DateTime.Now;
            return this;
        }

        /// <summary>
        /// 暂停租户
        /// </summary>
        public virtual Tenant Suspend()
        {
            Status = TenantStatus.Suspended;
            IsEnabled = false;
            return this;
        }

        /// <summary>
        /// 禁用租户
        /// </summary>
        public virtual Tenant Disable()
        {
            Status = TenantStatus.Disabled;
            IsEnabled = false;
            return this;
        }

        /// <summary>
        /// 启用租户
        /// </summary>
        public virtual Tenant Enable()
        {
            IsEnabled = true;
            if (Status == TenantStatus.Disabled)
            {
                Status = TenantStatus.Active;
            }
            return this;
        }

        /// <summary>
        /// 设置管理员信息
        /// </summary>
        public virtual Tenant SetAdminInfo(string adminEmail, string? adminPhoneNumber = null)
        {
            AdminEmail = Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail));
            AdminPhoneNumber = adminPhoneNumber;
            return this;
        }

        /// <summary>
        /// 设置连接信息
        /// </summary>
        public virtual Tenant SetConnectionInfo(string? connectionString, string? host = null)
        {
            ConnectionString = connectionString;
            Host = host;
            return this;
        }

        /// <summary>
        /// 设置订阅信息
        /// </summary>
        public virtual Tenant SetSubscriptionInfo(
            DateTime? subscriptionStartTime,
            DateTime? subscriptionEndTime,
            int maxUserCount,
            long maxStorageSize)
        {
            SubscriptionStartTime = subscriptionStartTime;
            SubscriptionEndTime = subscriptionEndTime;
            MaxUserCount = maxUserCount;
            MaxStorageSize = maxStorageSize;
            return this;
        }

        /// <summary>
        /// 设置试用信息
        /// </summary>
        public virtual Tenant SetTrialInfo(DateTime trialStartTime, DateTime trialEndTime)
        {
            TrialStartTime = trialStartTime;
            TrialEndTime = trialEndTime;
            Status = TenantStatus.Trial;
            return this;
        }

        /// <summary>
        /// 更新用户数量
        /// </summary>
        public virtual Tenant UpdateUserCount(int currentCount)
        {
            CurrentUserCount = currentCount;
            return this;
        }

        /// <summary>
        /// 更新存储使用量
        /// </summary>
        public virtual Tenant UpdateStorageUsage(long currentUsage)
        {
            CurrentStorageUsage = currentUsage;
            return this;
        }

        /// <summary>
        /// 延期订阅
        /// </summary>
        public virtual Tenant ExtendSubscription(TimeSpan extensionPeriod)
        {
            if (SubscriptionEndTime.HasValue)
            {
                SubscriptionEndTime = SubscriptionEndTime.Value.Add(extensionPeriod);
            }
            else
            {
                SubscriptionEndTime = DateTime.Now.Add(extensionPeriod);
            }

            ExtensionCount++;

            if (Status == TenantStatus.Expired)
            {
                Status = TenantStatus.Active;
            }

            return this;
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        public virtual Tenant UpdateSettings(string? settings)
        {
            Settings = settings;
            return this;
        }

        /// <summary>
        /// 更新功能开关
        /// </summary>
        public virtual Tenant UpdateFeatureSwitches(string? featureSwitches)
        {
            FeatureSwitches = featureSwitches;
            return this;
        }

        /// <summary>
        /// 更新自定义属性
        /// </summary>
        public virtual Tenant UpdateCustomProperties(string? customProperties)
        {
            CustomProperties = customProperties;
            return this;
        }

        /// <summary>
        /// 更新主题设置
        /// </summary>
        public virtual Tenant UpdateThemeSettings(string? themeSettings)
        {
            ThemeSettings = themeSettings;
            return this;
        }

        /// <summary>
        /// 更新最后访问时间
        /// </summary>
        public virtual Tenant UpdateLastAccessTime()
        {
            LastAccessTime = DateTime.Now;
            return this;
        }

        /// <summary>
        /// 检查租户是否过期
        /// </summary>
        public virtual bool IsExpired()
        {
            if (Status == TenantStatus.Disabled || Status == TenantStatus.Deleted)
            {
                return true;
            }

            if (Status == TenantStatus.Trial && TrialEndTime.HasValue)
            {
                return TrialEndTime.Value < DateTime.Now;
            }

            if (SubscriptionEndTime.HasValue)
            {
                return SubscriptionEndTime.Value < DateTime.Now;
            }

            return false;
        }

        /// <summary>
        /// 检查用户数量是否超限
        /// </summary>
        public virtual bool IsUserLimitExceeded()
        {
            return CurrentUserCount >= MaxUserCount;
        }

        /// <summary>
        /// 检查存储空间是否超限
        /// </summary>
        public virtual bool IsStorageLimitExceeded()
        {
            return CurrentStorageUsage >= MaxStorageSize;
        }

        /// <summary>
        /// 获取存储使用率（百分比）
        /// </summary>
        public virtual double GetStorageUsagePercentage()
        {
            if (MaxStorageSize <= 0)
            {
                return 0;
            }

            return Math.Round((double)CurrentStorageUsage / MaxStorageSize * 100, 2);
        }

        /// <summary>
        /// 获取用户使用率（百分比）
        /// </summary>
        public virtual double GetUserUsagePercentage()
        {
            if (MaxUserCount <= 0)
            {
                return 0;
            }

            return Math.Round((double)CurrentUserCount / MaxUserCount * 100, 2);
        }
    }
}